import React, { useEffect, useState, useRef } from 'react';
import { Button, Tag, Space, Modal, message } from 'antd';
import ProList from '@ant-design/pro-list';
import ProForm, { ModalForm } from '@ant-design/pro-form';
import { request, Link } from 'umi';
import dayjs from 'dayjs';
import { HomeOutlined } from '@ant-design/icons';
import InsertComponent from './components/InsertComponent';
import { PageContainer } from '@ant-design/pro-layout';
import UpdateComponent from './components/UpdateComponent';
import { api } from '@/global';
import { useAccess, Access } from 'umi';
type ClassesType = {
  id: number;
  className: string;

  classYear: string;
  deptName: string;
  professionalName: string;
  createTime: string;
  updateTime: string;
  classStatu: number;
};

const getWindowSize: any = () => ({
  innerHeight: window.innerHeight,
  innerWidth: window.innerWidth,
});

export default () => {
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const actionRef = useRef<ActionType>();
  const access = useAccess();
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };

  useEffect(() => {
    window.addEventListener('resize', handleResize);
  }, []);

  function reloadPage() {
    actionRef.current?.reload();
  }

  return (
    <PageContainer
      waterMarkProps={{
        content: '山西工程技术学院',
      }}
      header={{
        title: '班级管理',
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '组织管理',
            },
            {
              path: '',
              breadcrumbName: '班级管理',
            },
          ],
        },
      }}
    >
      <ProList<ClassesType>
        toolBarRender={() => {
          return [
            <Access key="insert" accessible={access.normalButtonFilter('CLASSES:INSERT')}>
              <InsertComponent key="insert" reloadPage={reloadPage} />
            </Access>,
          ];
        }}
        actionRef={actionRef}
        showActions="hover"
        grid={{
          gutter: windowSize.innerWidth < 535 ? 32 : 16,
          column: windowSize.innerWidth < 535 ? 1 : 2,
        }}
        search={{}}
        rowKey="id"
        headerTitle="班级列表"
        request={async (params = {}) =>
          request<{
            data: ClassesType[];
          }>(api.getClassesList, {
            method: 'POST',
            data: {
              ...params,
            },
          })
        }
        pagination={{
          pageSize: 5,
        }}
        metas={{
          title: {
            dataIndex: 'className',
            title: '班级名称',
            render: (_, row) => {
              return (
                <div style={{ fontWeight: 900 }}>
                  <HomeOutlined />
                  &nbsp;&nbsp;
                  {row.className}
                </div>
              );
            },
          },
          content: {
            dataIndex: '',
            search: false,
            render: (_, row) => {
              return (
                <div key={row.id}>
                  <Space size={2}>
                    <Tag color="blue" key={row.id}>
                      {row.deptName || '请选择系别'}
                    </Tag>
                    <Tag color="green" key={row.id}>
                      {row.professionalName || '请选择专业'}
                    </Tag>
                  </Space>
                  <br />
                  <br />
                  <Space size={2} direction="vertical">
                    <div>
                      <span>创建时间: {dayjs(row.createTime).format('YYYY MM-DD HH:mm:ss')}</span>
                    </div>
                    <div>
                      <span>修改时间: {dayjs(row.updateTime).format('YYYY MM-DD HH:mm:ss')}</span>
                    </div>
                  </Space>
                </div>
              );
            },
          },
          subTitle: {
            dataIndex: 'classStatu',
            render: (_, row) => {
              return (
                <Space size={2}>
                  <Tag color="#42bfac" key={row.id}>
                    {row.classYear}级
                  </Tag>
                  <Tag
                    color="blue"
                    key={row.id}
                    color={
                      row.classStatu >= 1
                        ? row.classStatu == 1
                          ? '#eccc68'
                          : '#dfe4ea'
                        : '#70a1ff'
                    }
                  >
                    {row.classStatu >= 1 ? (row.classStatu == 1 ? '在校' : '已毕业') : '其他'}
                  </Tag>
                </Space>
              );
            },
            search: false,
          },
          actions: {
            cardActionProps: 'actions',
            render: (_, row) => [
              <Access
                key={'select' + row.id}
                accessible={access.normalButtonFilter('CLASSES:SELECT')}
              >
                <Link
                  key={'select' + row.id}
                  to={'/organizational_management/classes_manager/classes_info?classId=' + row.id}
                >
                  <a>查看</a>
                </Link>
              </Access>,
              <Access
                key={'update' + row.id}
                accessible={access.normalButtonFilter('CLASSES:UPDATE')}
              >
                <UpdateComponent key={'update' + row.id} currentRow={row} reloadPage={reloadPage} />
              </Access>,
              <Access
                key={'select' + row.id}
                accessible={access.normalButtonFilter('CLASSES:DELETE')}
              >
                <ModalForm<{
                  name: string;
                  company: string;
                }>
                  key="delte"
                  title="删除班级"
                  trigger={<a>删除</a>}
                  autoFocusFirstInput
                  modalProps={{
                    onCancel: () => console.log('run'),
                  }}
                  onFinish={async (values) => {
                    const result = await request(
                      api.deleteClaasesById,

                      {
                        method: 'POST',
                        data: {
                          id: row?.id,
                        },
                        skipErrorHandler: true,
                      },
                    );

                    if (result.success) {
                      message.info('删除成功');
                      actionRef.current?.reload();
                      return true;
                    } else {
                      message.error('删除失败');
                      return true;
                    }
                  }}
                >
                  是否删除&nbsp;&nbsp;
                  <span style={{ fontWeight: 900, fontSize: 25, color: '#3498db' }}>
                    {row?.className}
                  </span>
                  &nbsp;&nbsp;班级
                </ModalForm>
              </Access>,
            ],
            search: false,
          },
          status: {
            // 自己扩展的字段，主要用于筛选，不在列表中显示
            title: '状态',
            dataIndex: 'statu',
            valueType: 'select',

            request: () => {
              const list: any[] = [];
              list.push({
                label: '全部',
                value: 0,
              });
              list.push({
                label: '在校',
                value: 1,
              });
              list.push({
                label: '已毕业',
                value: 2,
              });
              list.push({
                label: '其他',
                value: 3,
              });
              return list;
            },
          },
          Dept: {
            title: '系部',
            dataIndex: 'dept',
            valueType: 'select',
            request: async () => {
              const deptData = await request(api.getAllDept, {});
              const list: any[] = [];
              list.push({
                label: '全部',
                value: 0,
              });
              deptData.data.map((item: deptTyp) => {
                list.push({
                  label: item.deptName,
                  value: item.id,
                });
              });

              return list;
            },
          },
          prfessional: {
            title: '专业',
            dataIndex: 'professional',
            valueType: 'select',
            request: async () => {
              const conditionData = await request(api.getSimpleProfessional, {});

              const list: any[] = [];
              list.push({
                label: '全部',
                value: 0,
              });
              conditionData.data.map((item: professionalType) => {
                list.push({
                  label: item.professionalName,
                  value: item.id,
                });
              });

              return list;
            },
          },
          year: {
            title: '年级',
            dataIndex: 'year',
            valueType: 'select',
            request: async () => {
              const { data } = await request(api.getEarlyYear, {});

              let year = dayjs().year();

              const list: any[] = [];
              list.push({
                label: '全部',
                value: 0,
              });

              while (year - 2000 - data >= 0) {
                list.push({
                  label: String(year - 2000) + '级',
                  value: year - 2000,
                });
                year = year - 1;
              }

              return list;
            },
          },
        }}
      />
    </PageContainer>
  );
};
